//新版基础函数
var f = {
    init:function() {
        log("程序初始化")
    },
    //post
    post : function(url,data){
        var res = http.post(url, data);
        var data = res.body.string();
        if(data){
            // log(data);
            return data;
        }
    },
    //get
    get : function(url){
        var res = http.get(url);
        var data = res.body.string();
        if(data){
            return data;
        }
    },
    //读取本地数据
    getLocal:function ( name, key) {
        const storage = storages.create(name);  //创建storage对象
        if (storage.contains(key)) {
            return storage.get(key);
        };
        //默认返回undefined
    },
    //基础函数
    active:function(pkg,n){
        if(!n){n=5}
        if(  currentPackage() == pkg ){
            log("应用在前端");
            return true;
        }else{
            log("启动一次应用");
            app.launch(pkg);
            sleep(1000)
            f.ms({"textMatches":"允许|始终允许"},true)
            sleep(1000*n)
        }
    },
    //准备点击
    click:function (x,y,sleeptime,name){
        if ( ! sleeptime ){sleeptime = 1}
        if ( name ){
            log('准备点击->'+name,"x:",x,"y:",y);
        }else{
            log('准备点击坐标->', "x:",x,"y:",y);
        }
        if( x > 0  && y > 0  ){
            threads.start(function(){
                //在新线程执行的代码
                click(x,y);
            });
            // click(x,y);
            sleep(sleeptime*1000);
            return true
        }else{
            log('坐标错误');
        }
    },
    //点击obj
    clickObj:function (obj,sleeptime,name){
        if ( ! sleeptime ){ sleeptime == 1 } 
        log(  name ? ("准备点击对象->" + name) : "点击未命名对象" )
        x = obj.bounds().centerX()
        y = obj.bounds().centerY()
        return f.click(x,y,sleeptime,name)
    },
    //穿透点击
    clickTrue:function(obj,sleeptime,name,lun){
        sleeptime ? sleeptime : 1
        let result = false;
        lun ? lun : 3
        for (let i=0;i<lun;i++){
            if (  obj && obj.clickable() ){
                obj.click();
                log(  name ? ("准备穿透点击对象->" + name) : "准备穿透点击未命名对象" )
                result = true
                break
            }
            obj = obj.parent()
        }
        if ( result ) { sleep(sleeptime * 1000) }
        return result
    },
    //正则点击
    ms:function (obj,clicks,sleeptimes,name,findtime,lun){
        if (!sleeptimes) { sleeptimes = 1}
        if (!findtime) { findtime = 200}
        if (!lun) { lun = 3}

        var txt = '';
        for(let key in obj){
            if ( key.search("Matches") > 0 ){
                eval("var matches = /" + obj[key] + "/")
                txt = txt + key+'('+matches+').'
            }else if( key ==  'boundsInside' ){
                txt = txt + key+'('+obj[key]+').'
            }else{
                txt = txt + key+'("'+obj[key]+'").'
            }
        }
        var txt = "let objs = "+txt+"findOne("+findtime+");"
        log(txt)
        eval(txt)
        if ( objs ) {
            log( '找到==>' + objs.text() || objs.desc() || objs.id() || objs.className() )
            if ( clicks ){
                name = obj['textMatches'] || obj['descMatches'] || obj['idMatches'] || obj['text'] || obj['desc'] || obj['id']
                if (lun < 1 || !f.clickTrue( objs,sleeptimes,name,lun )){
                    log('准备坐标点击')
                    return f.clickObj( objs,sleeptimes,name );
                }
            }
            return true;
        }
    },
    rd:function (min,max){
        if (min<=max){
            return random(min,max)
        }else{
            return random(max,min)
        }
    },
    moveTo:function (x,y,x1,y1,times){
        swipe(x,y,x1,y1,times);
        sleep(1000);
    }
}
f.init()


//批查打印app参数
function printAll( ways ) {
    if (!ways){
        ways = 'className'
    }
    if (ways = 'className'){
        var all_Info = classNameMatches(/.*/).find();
    }else
    if (ways == 'text'){
        var all_Info = textMatches(/.*/).find();
    }else
    if (ways == 'id'){
        var all_Info = idMatches(/.*/).find();
    }else{
        eval( 'var all_Info = ' + ways + '.find();'  )
    }
    
    if ( all_Info ){
        for (var i = 0;i<all_Info.length;i++){
            var d = all_Info[i];
            log(i,d.id(),d.text(),"desc:"+d.desc(),'"className":"'+d.className()+'"',
            "clickable->"+d.clickable(),'selected->'+selected(),"depth->"+d.depth(),
            d.bounds().centerX(),d.bounds().centerY())
        }
    }else{
        log('没有找到任何相关的节点')
    }
}


printAll()



//河马ip
function hmip(){
    var result = shell("ipclient faa31f81bfea4124995972d5dc016b57 1", true);
    // console.show();
    // log(result);
    if(result.code == 0){
        toastLog("vpn 执行成功");
      return true
    }else{
        toastLog(result)
        toastLog("vpn 执行失败！请到控制台查看错误信息");
    }
}


//设备大师
function sbds(){
    let fix = false
    var start = false
    var timeLine = new Date().getTime()
    while ( new Date().getTime() - timeLine < 5 * 60 * 1000 ) {

        if ( f.active( appinfo.sbdsbid , 5)  ){

            if (fix && f.ms({"text":"修改设备"},false,rd(2,3) )){
                return true
            }else
            if ( f.ms({"text":"修改设备"},true,rd(2,3) )   ){
                start = true;
            }else if ( start && f.ms("id","brand",true,rd(2,3) ) ){

                var phonelist = [ "XIAOMI","HUAWEI","SAMSUNG","HONOR","vivo"]
                if ( f.ms({"text":phonelist[rd(0,4)],"depth":4},true,rd(1,2)) ) {
                    f.ms("text","下一步",true,rd(2,3))
                }else{
                    f.ms("id","back",true,rd(2,3))
                }
                
            }else if( start && f.ms("text","立即清理",false,rd(2,3)) ){
                f.ms("text","以吾之力",true,1)
                f.ms("text","QQ浏览器",true,1)

                if ( f.ms("text","立即清理",true,rd(10,15)) ){
                    fix = true
                }
            }else{
                f.ms("id","back",true,rd(2,3))
            }
        }
        sleep(1000);
    }
}


//抹机王
function MJW(){
    let fix = false
    var start = false
    var timeLine = new Date().getTime()
    while ( new Date().getTime() - timeLine < 2 * 60 * 1000 ) {

        if ( f.active( appinfo.mjwbid , 3)  ){

            if ( start && f.ms({"text":"任务结束-点击返回"},true,f.rd(2,3) )  ){
                return true
            }else
            if ( f.ms({"text":"一键抹机/一键新机"},true,f.rd(2,3) )   ){
                start = true;
            }
        }
        sleep(2000);
    }
}

//抹机王参数
function getMJW() {
    let fix = false;
    var start = false;
    var timeLine = new Date().getTime();
    while (new Date().getTime() - timeLine < 3 * 60 * 1000) {
        if (  f.active(appinfo.mjwbid, 3)  ) {
            
            if ( f.ms( {"text":"查看详细"}) ){
                log("设备信息界面");
                appinfo.imei = id("wipedev_tv_imei").findOne(100).text();
                // appinfo.oaid = id("deviceinfo_tv_androidId").findOne(100).text();
                appinfo.model = id("wipedev_tv_model").findOne(100).text();
                appinfo.brand = id("wipedev_tv_brand").findOne(100).text();
                appinfo.phone = id("wipedev_tv_phone").findOne(100).text();

                // console.show()
                log( appinfo );
                return true;
            }

        }
    }
}


//设备大师
function sbdsJk(){

    // f.active(appinfo.sbdsbid, 5)
    var result = shell("setphone" ,true);

    // eval( 'var result = shell("setphone -m vivo -b vivo -o ' + phoneMode[rd(0,5)] +'" ,true)'  )
    // var result = shell("setphone -m vivo -b vivo -o Y85A" ,true);
    // console.show();
    log(result);
    if(result.code == 0){
        toastLog("一键新机 执行成功")
    }else{
        toastLog("一键新机 执行失败！请到控制台查看错误信息")
    }

    eval( 'var result = shell("pm clear '+ appinfo.bid +'",true)'  )
    // eval( 'var result = shell("pm clear '+ appinfo.llq +'",true)'  )
    // var result = shell("pm clear com.youxiang.soyoungapp",true)
    log(result);
    if(result.code == 0){
        toastLog("一键清理 执行成功");
        return true
    }else{
        toastLog("一键清理 执行失败！请到控制台查看错误信息");
    }

    
    recents();
    sleep(3000)

    if ( f.ms({"descMatches":"移除设备大师.*"},true,3)){
        return true
    }
}


//设备大师参数信息
function getsbds() {
    let fix = false;
    var start = false;
    var timeLine = new Date().getTime();
    while (new Date().getTime() - timeLine < 3 * 60 * 1000) {
        if (  f.active(appinfo.sbdsbid, 3)  ) {
            
            if ( f.ms({"text":"当前设备"} ) ){
                log("设备信息界面");
                appinfo.imei = id("imei").findOne(100).text();
                appinfo.oaid = id("android_id").findOne(100).text();
                appinfo.model = id("phone_model").findOne(100).text();
                appinfo.brand = id("phone_brand").findOne(100).text();

                // console.show()
                log( appinfo );
                home()
                sleep(1000)
                return true;
            }

        }
    }
}





//上传idfa
function Idfa(other){
    let postArr = {};
    postArr['service'] = 'Idfa.idfa';
    postArr['name'] = appinfo.name;
    postArr['idfa'] = appinfo.imei || device.getIMEI() || new Date();
    postArr['appid'] = appinfo.oaid || device.getAndroidId()
    postArr['phoneos'] = appinfo.model || device.model
    postArr['password'] = appinfo.brand || device.brand
    postArr['other'] = other ? other : "成功";
    postArr['phone'] = appinfo.phone;
    // postArr['account'] = "lon:" + appinfo.lon + "; lat:" + appinfo.lat;
    let data = f.post("http://wenfree.cn/api/Public/idfa/",postArr);
    log(data)
    toastLog("上传成功")
}
//上传idfa


//上传idfa
function Idfa_error(other){
    let postArr = {};
    postArr['service'] = 'Idfa.idfa';
    postArr['name'] = appinfo.name + '错误';
    postArr['idfa'] = appinfo.imei || device.getIMEI() ||new Date();
    postArr['appid'] = appinfo.oaid || device.getAndroidId()
    postArr['phoneos'] = appinfo.model || device.model
    postArr['password'] = appinfo.brand || device.brand
    postArr['other'] = other ? other : "成功";
    let data = f.post("http://wenfree.cn/api/Public/idfa/",postArr);
    log(data)
    toastLog("上传成功")
}


//主程序
function main(){

    var kill = true
    var timeLine = new Date().getTime();
    f.active(appinfo.bid, 5)
    while (new Date().getTime() - timeLine < (40+f.rd(1,3)) * 1000) {
        
    
            f.ms({"text":"同意"},true,2)
            f.ms({"text":"同意"},true,2)
            f.ms({"text":"下一步"},true,2)
            f.ms({"text":"允许"},true,2)
            if( f.ms({"id":"tv_text"},true,2)){   
                recents();
                sleep(3000)
                if ( f.ms({"descMatches":"移除佛山.*"},true,2)){
                    // return true
                    kill = false
                    f.active(appinfo.bid, 5)
                }
            }


            if ( f.ms({"text":"首页"},true,1) &&  f.ms({"text":"观点"},true,2)    ){
                
            }
            
            if ( f.ms({"id":"tv_title"})  ){
                return true
            }

            sleep(1000)
        
    }

    Idfa_error('超时')
}




function checkIp(){
    url = "http://wenfree.cn/api/Public/idfa/?service=Ip.Checkip&ip=&name=" + appinfo.name
    log(url)
    r = f.post(url,{})
    log(r)
    if (r){
        r = JSON.parse(r)
        if ( r.data.state == "ok"){
            toastLog(r.data.ip + "可以使用")
            return true
        }
    }
}

function openUrl(){
    url = "https://content.foshanplus.com/download.html?cid=1123"
    app.openUrl(url)
    let i = 0
    while ( i < 30 ){
        f.ms({"textMatches":"QQ浏览器"},true,2)
        f.ms({"textMatches":"始终"},true,2)
        f.ms({"textMatches":"知道了"},true,2)
        f.ms({"textMatches":"允许"},true,2)
        f.ms({"textMatches":"允许"},true,2)
        if( f.ms({"textMatches":".*下载.*"},true,f.rd(5,6))){
            if( f.ms({"textMatches":"直接下载"},true,f.rd(4,6))){
                // eval( 'var result = shell("pm clear '+ appinfo.llq +'",true)'  )
            }
            return true
        }
        i++
        sleep(1000)
    }
}



function openUrlByQQ(){
    // app.openUrl(info.h5)
    // sleep(5000)
    let i = 0
    while ( i < 12 ){
        

        if( f.ms({"id":"small_download_link"},true,f.rd(2,3))){
            recents();
            sleep(2000)
            f.ms({"descMatches":"移除Chrome.*"},true,3)
            return true
        }
        i++
        sleep(1000)
    }
}

function openUrlByChrome(){
    // app.openUrl(info.h5)
    // sleep(5000)
    let i = 0
    while ( i < 12 ){
        if ( f.active(appinfo.chrome, 3) ){
            if( f.ms({"id":"small_download_link"},true,f.rd(2,3))){
                recents();
                sleep(2000)
                f.ms({"descMatches":"移除Chrome.*"},true,3)
                return true
            }
            i++
            sleep(1000)
        }
    }
}



//设备大师参数信息
function gz_ip() {
    
    var hostIpText = "未取";
    var timeLine = new Date().getTime();
    while (new Date().getTime() - timeLine < 3 * 60 * 1000) {
        if (  f.active(appinfo.gzbid, 3)  ) {
            if ( hostIpText == "未取"){
                
                hostIpText = id("hostIpText").findOne(5000).text()
                log(hostIpText,"hostIpText")
                f.ms({"text":"切换节点"},true,2)
            }else{
                newHostIP = id("hostIpText").findOne(5000)
                if ( newHostIP ) {
                    log(newHostIP.text(),"newHostIP")
                    if (newHostIP.text() != hostIpText ){
                        return true
                    }
                }
            }
            
            sleep(1000)
        }
    }
}


function changeMaps(lon,lat){
    
    // lon 经度, lat 纬度
    // 113.65 34.76	
    

    // localText = 'var result = shell("setlocation --lat ' + 34.7 + f.rd(10000,99999) + ' --lon ' + 113.8 + f.rd(10000,99999) +'" ,true)';
    localText = 'var result = shell("setlocation --lat ' + lat + ' --lon ' + lon +'" ,true)';
    log(localText)
    eval(localText)

    log(result);
    if(result.code == 0){
        toastLog("地址位置 执行成功");
        return true
    }else{
        toastLog("地址位置 执行失败！请到控制台查看错误信息");
    }



}

// 正式开始编代码
var width = 720;
var height = 1440;
var width = device.width;
var height = device.height;
var phoneMode = device.brand;

log([currentPackage(),currentActivity(),width,height]);
var appinfo = {}
appinfo.name = "佛山1125";
appinfo.bid = "com.newgen.fs_plus";
appinfo.llq = "com.tencent.mtt";
appinfo.chrome = "com.android.chrome"
appinfo.gzbid = "com.deruhai.guangzi";
appinfo.sbdsbid = "com.longene.setcardproperty";
appinfo.mjwbid = "com.yztc.studio.plugin";
appinfo.lat = "";
appinfo.lon = "";
info ={};

info.h5 = "https://content.foshanplus.com/download.html?cid=1125"
info.url = "https://fsnews.oss-cn-shenzhen.aliyuncs.com/channel/5.0.0/1123.apk"



function all(){
    while (true){
        
        try{
            start_time = new Date().getHours()
            if ( start_time >= 0 ){
                if ( true || checkIp() ){
                    
                    if ( MJW() ){
                        
                        if ( getMJW() ){

                            
                            if ( main() ){
                                Idfa("观点")
                            }
                            

                        }

                    }
                    // hmip()
                    gz_ip()
                    
                }
        
        
                sleep(3000)
                f.ms({"textMatches":".*关闭.*"},true,2)

            }else{

                log('时间不正确')
                sleep(3000)
            }


        }catch(e){
            log(e)
            sleep(5*1000)
            // hmip()
            gz_ip()
        }

        sleep(3000)
        f.ms({"textMatches":".*关闭.*"},true,2)

    }
}

// console.show()
all()


// openUrl()

// openUrlByQQ()








